import dayjs from 'dayjs'
import API from '../CloudServer/send.js'
import { findDifference } from '../utils/index.js'
import { sendDingTalkMsgFn } from './sendDingTalkMsg.js'

// 同步预处理函数-查询task表要执行的任务
const syncFn = async (params, result, pool, DingTalkToken) => {
  const sql = `SELECT * FROM task WHERE status = ?`
  pool.all(sql, [1], (err, rows) => {
    if (err) {
      result && result.status(500).json(err)
    } else {
      rows.forEach((row) => {
        syncCloneFn(row, params.cookies, null, pool)
      })
      result &&
        setTimeout(() => {
          result.status(200).json({ res_code: 0, res_message: '已执行!' })
        }, 2000)
    }
  })
}
// 执行检查任务状态函数
const checkBatchTaskFn = (params, count = 0) => {
  count++
  if (count > 10) {
    return
  }
  const { taskId, type, cookies, result, task_name, added, login_name } = params
  API.checkBatchTask(
    {
      taskId,
      type,
    },
    cookies,
  ).then((res) => {
    if (res.data.res_code == 0 && res.data.taskStatus == 4) {
      sendDingTalkMsgFn({ task_name, added, login_name })
      result && result.status(200).json(res.data)
      return
    }
    if (res.data.res_code == 0 && res.data.taskStatus == -1) {
      // 结束循环
      result && result.status(500).json(res.data)
      return
    }
    if (res.data.res_code == 0 && res.data.taskStatus != 4 && res.data.taskStatus != -1) {
      // 进入循环
      setTimeout(() => {
        checkBatchTaskFn(params, count)
      }, 3000)
    }
  })
}
// 执行同步任务函数
const syncCloneFn = async (row, cookies, result, pool) => {
  const shareParams = {
    noCache: Math.random(),
    shareId: row.share_id,
    fileId: row.share_file_id,
    shareDirFileId: row.share_file_id,
    isFolder: true,
    shareMode: row.share_mode,
    orderBy: 'filename',
    descending: false,
    accessCode: row.access_code || '',
  }
  const shareFilesInfo = await API.getShareInfoAPI(shareParams, cookies)
  const params = {
    mediaType: '0',
    folderId: String(row.save_path_id),
    orderBy: 'filename',
    descending: false,
  }

  //   console.log('shareFilesInfo >>>', shareFilesInfo)
  if (shareFilesInfo.res_code != 0 && !shareFilesInfo.fileList) {
    result && result.status(500).json(shareFilesInfo)
    return
  }
  const ListFilesInfo = await API.sendListFiles(params, cookies)
  //   console.log(' ListFilesInfo>>>', ListFilesInfo.data)
  if (!ListFilesInfo.data) {
    result && result.status(500).json(ListFilesInfo)
    return
  }
  const targetFilesInfo = ListFilesInfo.data.fileListAO

  //   added 新增的文件
  const { added: addedFile } = findDifference(targetFilesInfo.fileList, shareFilesInfo.fileList, 'md5')
  let added = []
  if (row.save_type == 1) {
    const { added: addedFolder } = findDifference(targetFilesInfo.folderList, shareFilesInfo.folderList, 'name')
    added = [...addedFile, ...addedFolder]
  } else {
    added = [...addedFile]
  }
  //   console.log('added >>>', added)
  if (added.length <= 0 || !added) {
    // console.log(' 没有需要同步的文件>>>', row.task_name)
    result && result.status(200).json({ res_code: 0, res_message: '没有需要同步的文件' })
    return
  }
  const taskInfos = added.map((item) => {
    return { fileId: item.id, fileName: item.name, isFolder: 0 }
  })
  const taskParams = {
    type: 'SHARE_SAVE',
    taskInfos: JSON.stringify(taskInfos),
    targetFolderId: row.save_path_id,
    shareId: row.share_id,
  }
  // 执行批量任务-保存文件
  const createBatchTaskRes = await API.createBatchTask(taskParams, cookies)
  if (!createBatchTaskRes.data.taskId) {
    result && result.status(500).json(createBatchTaskRes)
    return
  }

  const current_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
  console.log(current_time)
  pool.run('UPDATE task SET update_time = ?, episode = ? WHERE id = ?', [
    current_time,
    shareFilesInfo.fileList.length,
    Number(row.id),
  ])

  setTimeout(() => {
    checkBatchTaskFn({
      taskId: createBatchTaskRes.data.taskId,
      type: 'SHARE_SAVE',
      cookies,
      result,
      task_name: row.task_name,
      added,
      login_name: row.login_name,
    })
  }, 3000)
}
export { syncFn, syncCloneFn }
